package com.truthbean.ssm.demo.test;

import org.apache.log4j.Logger;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Slf4jLog;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.webapp.WebAppContext;

import java.io.File;


/**
 * @author Truthbean
 * @since 2015-12-23 18:54:07
 */

public class Starter {

    static {
        try {
            Log.setLog(new Slf4jLog());
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    private Starter() {
    }

    public static void main(String[] args) throws Exception {
        final Logger logger = Logger.getLogger(Starter.class);
        String webapp = "src/main/webapp/";
        logger.info("webapp location is: " + webapp);

        final File file = new File(webapp);
        if (!file.exists()) {
            webapp = "."; // prod env
        }

        logger.info("webapp location is: " + webapp);

        /*Server server = new Server(8080);
        WebAppContext root = new WebAppContext();

        root.setContextPath("/ssm");
        root.setDescriptor(webapp + "/WEB-INF/web.xml");
        root.setResourceBase(webapp);

        server.setHandler(root);

        server.start();

        server.join();*/

        Server server = new Server();

        HttpConfiguration https_config = new HttpConfiguration();
        https_config.setSecureScheme("https");
        https_config.setSecurePort(8443);
        https_config.setOutputBufferSize(32768);
        https_config.addCustomizer(new SecureRequestCustomizer());

        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath("src/main/resources/config/jetty/keystore");
        sslContextFactory.setKeyStorePassword("OBF:1v2j1uum1xtv1zej1zer1xtn1uvk1v1v");
        sslContextFactory.setKeyManagerPassword("OBF:1v2j1uum1xtv1zej1zer1xtn1uvk1v1v");

        ServerConnector httpsConnector = new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory, "http/1.1"),
                new HttpConnectionFactory(https_config));
        httpsConnector.setPort(8443);
        httpsConnector.setIdleTimeout(500000);
        server.addConnector(httpsConnector);

        WebAppContext root = new WebAppContext();

        root.setContextPath("/ssm");
        root.setDescriptor(webapp + "/WEB-INF/web.xml");
        root.setResourceBase(webapp);

        root.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
        root.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");

        server.setHandler(root);

        server.start();

        server.join();

    }

}
